//
//  SettingViewController.m
//  nmrsc
//
//  Created by xumckay on 16/1/20.
//  Copyright © 2016年 bric. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingTableViewCell.h"
@interface SettingViewController ()

@property (strong,nonatomic)UITableView *tableView;
@property (strong,nonatomic)NSArray *titleArr;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor=[UIColor whiteColor];
    NAVBAR(@"设置管理");
    UIButton *backBtn=[[UIButton alloc]initWithFrame:CGRectMake(0,0,8.5,15)];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,64,kDeviceWidth,kDeviceHeight)];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    [self addLoginOutBtn];
    [self.view addSubview:_tableView];
    
    if (!KversonIsAppstore) {
        _titleArr=@[@"修改密码",@"地理位置信息",@"WIFI环境下自动更新客户端",@"清除缓存"];
    }
    else
    {
        _titleArr=@[@"修改密码",@"地理位置信息",@"清除缓存"];
     }
}

-(void)addLoginOutBtn
{
    UIView*footerView=[[UIView alloc]initWithFrame:CGRectMake(0,0,kDeviceWidth,kDeviceHeight/5*3)];
    
    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth/4,kDeviceHeight/2,kDeviceWidth/2,35)];
    [button setTitle:@"退出当前账号" forState:UIControlStateNormal];
    [button setTitleColor:COLOR(36, 148, 88, 1) forState:UIControlStateNormal];
    button.titleLabel.textAlignment=NSTextAlignmentCenter ;
    [button setBackgroundColor:[UIColor whiteColor]];
    button.layer.borderWidth=1;
    button.layer.cornerRadius=8;
    button.layer.borderColor=COLOR(36, 148, 88, 1).CGColor;
    button.clipsToBounds=YES;
    [button addTarget:self action:@selector(loginOutBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:button];
    footerView.userInteractionEnabled=YES;
    _tableView.tableFooterView=footerView;
    
}

-(void)loginOutBtnClicked
{
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
    [[NSUserDefaults standardUserDefaults]setObject:dict forKey:@"user"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"loginOutBtnClicked" object:nil];
}


#pragma mark   ---UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _titleArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!KversonIsAppstore) {
        static NSString*identifier=@"cell1";
        SettingTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell=[[SettingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.titleLabel.text=[_titleArr objectAtIndex:indexPath.row];

        switch (indexPath.row) {
            case 0:
            {
               cell.detailLabel.text=@"";
                cell.autoUpdateSwitch.hidden=YES;
                cell.arrowView.hidden=NO;
            }
                break;
            case 1:
            {
                cell.detailLabel.frame=CGRectMake(kDeviceWidth-100-15-20,0,100,45);
                cell.detailLabel.text=@"";
                cell.autoUpdateSwitch.hidden=YES;
                cell.arrowView.hidden=NO;
            }
                break;
            case 2:
            {
                cell.detailLabel.text=@"";
                cell.autoUpdateSwitch.hidden=NO;
                cell.arrowView.hidden=YES;
            }
                break;
            case 3:
            {
                cell.detailLabel.frame=CGRectMake(kDeviceWidth-100-15,0,100,45);
                cell.autoUpdateSwitch.hidden=YES;
                cell.arrowView.hidden=YES;
                cell.detailLabel.text=[NSString stringWithFormat:@"%@M",[self calculateMemory]];
                
            }
                break;
            default:
                break;
        }
        return cell;
        
    }else
    {
        static NSString*identifier=@"cell2";
        SettingTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell=[[SettingTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.autoUpdateSwitch.hidden=YES;
        cell.titleLabel.text=[_titleArr objectAtIndex:indexPath.row];
        switch (indexPath.row) {
            case 0:
            {
                cell.detailLabel.text=@"";
                cell.arrowView.hidden=NO;
            }
                break;
            case 1:
            {
                cell.detailLabel.frame=CGRectMake(kDeviceWidth-100-15-20,0,100,45);
                cell.detailLabel.text=@"";
                cell.arrowView.hidden=NO;
            }
                break;
            case 2:
            {
                cell.detailLabel.frame=CGRectMake(kDeviceWidth-100-15,0,100,45);
                cell.arrowView.hidden=YES;
                cell.detailLabel.text=[NSString stringWithFormat:@"%@M",[self calculateMemory]];
                
            }
                break;
            default:
                break;
        }
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(!KversonIsAppstore)
    {
        if (indexPath.row==3) {
            [self tapClearMemory];
            
        }
    }
    else
    {
        if (indexPath.row==2) {
            [self tapClearMemory];
        }
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}

//计算剩余多少M缓存
-(NSString*)calculateMemory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];

    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    NSString* finalSize=[NSString stringWithFormat:@"%.2f",folderSize/(1024.0*1024.0)];
    return finalSize;
}


- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

-(void)tapClearMemory
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除后，图片等多媒体信息需重新下载查看。" message:nil preferredStyle:0];
    UIAlertAction *clearAction = [UIAlertAction actionWithTitle:@"清除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                                  {
                                      [self clearMemory];
                                  }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popoverPresentationController];
    }];
    [clearAction setValue:COLOR(145, 194, 38, 1) forKey:@"_titleTextColor"];
    
    [alertController addAction:clearAction];
    [alertController addAction:cancleAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


- (void)clearMemory
{
    //彻底清除缓存第一种方法
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    HLManager *hl=[HLManager sharedManager];
    
    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
    [hl showHudText:[NSString stringWithFormat:@"已清除%.2fM缓存",[self folderSizeAtPath:path]] detailsText:nil afterDelay:1];
    NSLog(@"%@",str);
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    [_tableView reloadData];
}


//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

-(void)backClicked
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
